#批量备份重构版本 V1.0.2
#在使用脚本前先确保在本机的python环境中装好 paramiko openpyxl模块
#按照excel模板添加设备将excel和py脚本放在同一目录下
#目前只支持华为和华三，如有其他厂家的可自行添加

import paramiko
import time
from openpyxl import load_workbook
from concurrent.futures import ThreadPoolExecutor


def device_config(ip,user,passwd,hostname,company):
    """创建ssh客户端"""
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip,port=22,username=user,password=passwd)
        clinet = ssh_client.invoke_shell()
        print(f"{ip} 连接成功！")
    except:
        print(f"{ip} 连接失败！")
    else:
        #  判断设备厂家
        if company == "Huawei":
            clinet.send('n\n')
            clinet.send('screen-length 0 temporary\n')
        elif company == "H3C":
            clinet.send('n\n')
            clinet.send('screen-length disable\n')
        #  获取设备配置
        clinet.send('display current-configuration \n')
        print(f"获取到 {hostname} 的配置，请稍等")
        # 为防止部分低性能的设备将等待15S 可根据设备性能自行更改延时时间
        time.sleep(15)


        if company == "Cisco":
            pass

        try:
            #将获取的配置写入到txt文本中
            config = clinet.recv(999999).decode()
            now = time.strftime('%Y-%m-%d', time.localtime())
            with open(f"./config/{now}-{hostname}-{ip}.txt",mode="w",encoding="utf-8") as f:
                f.write(config)
            print(f"{ip} 备份成功！")
        except:
            print(f"{ip} 备份失败！")
    finally:
        clinet.close()

def main():
    start = time.time()
    #  1.读取excel获取设备信息
    wb = load_workbook("./host.xlsx")
    ws = wb["Switch"]
    pool = ThreadPoolExecutor(ws.max_row)

    for row in range(2,ws.max_row+1):
        hostname = ws.cell(row,1).value
        ip = ws.cell(row,2).value
        user = ws.cell(row,3).value
        passwd = ws.cell(row,4).value
        company = ws.cell(row,5).value
        #  2.批量连接到ssh客户端
        pool.submit(device_config,ip,user,passwd,hostname,company)
    pool.shutdown(wait=True)
    end = time.time()

    print("配置备份完成！总共用时 %fs" %(end - start))


if __name__ == "__main__":
    main()